<template>
  <transition name="el-zoom-in-center">
    <div class="container" :style="{ overflow: isEdit ? 'hidden' : 'auto'}">
      <div class="main-header">
        <el-page-header :content="title" @back="goBack"></el-page-header>
      </div>

      <el-card class="steps-box-card" shadow="never" v-if="!isEdit">
        <div class="main-steps">
          <el-steps :active="active" finish-status="success" align-center>
            <el-step title="基础信息"></el-step>
            <el-step :title="isEdit?'修改单据':'新增单据'"></el-step>
          </el-steps>
        </div>
      </el-card>

      <div class="mt20" v-if="active == 0">
        <el-form class="form" ref="form" :model="form" :rules="rules" label-width="80px">
          <el-card class="main-lf-t" shadow="never">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名称">
                  <el-input v-model="nickName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在部门">
                  <el-select style="width: 100%;" v-model="form.deptName " placeholder="请选择所在部门"
                             @change="$forceUpdate()">
                    <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                               :value="item.deptName">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报销概述" prop="title">
                  <el-input v-model="form.title" placeholder="请输入报销概述"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="报销时间" prop="businessDate">
                  <el-date-picker style="width: 100%;" clearable v-model="form.businessDate"
                                  type="date" value-format="yyyy-MM-dd" placeholder="请选择提交报销时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="clStartTime">
                  <el-date-picker style="width: 100%;" v-model="form.clStartTime" type="datetime"
                                  clearable value-format="yyyy-MM-dd HH:00" format="yyyy-MM-dd HH:00"
                                  popper-class="hour-picker1" placeholder="请选择出差开始时间" @change="clStartTimeChange">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="clEndTime">
                  <el-date-picker style="width: 100%;" v-model="form.clEndTime" type="datetime"
                                  clearable value-format="yyyy-MM-dd HH:00" format="yyyy-MM-dd HH:00"
                                  popper-class="hour-picker1" placeholder="请选择出差结束时间" @change="clEndTimeChange">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出差地点" prop="city">
                  <el-cascader style="width: 100%;" v-model="city" :options="cityData"
                               :props="defaultPropsCa" @change='$forceUpdate()' clearable></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="途径地点" prop="passCity">
                  <el-cascader style="width: 100%;" v-model="passCity" :options="cityData"
                               :props="defaultPropsCa" @change='$forceUpdate()' clearable></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对应人员" prop="personnel">
                  <el-input v-model="form.personnel" placeholder="请输入对应人员"/>
                </el-form-item>
              </el-col>
            </el-row>


            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注"/>
            </el-form-item>
            <el-button style="float: right;margin-bottom: 20px;" type="primary" @click="submitOne">
              {{isEdit?'确认修改':'下一步'}}
            </el-button>
          </el-card>
        </el-form>
      </div>


      <div v-if="active == 1" v-loading="loading" element-loading-text="拼命加载中"
           element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-form class="form main-flex" ref="form" :model="form" label-width="70px">
          <div class="main-lf">
            <div class="main-lf-t">
              <el-card class="main-lf-t" shadow="never">
                <div class="label">基本信息</div>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户名称">
                      <el-input v-model="form.nickName" :readonly="isItMe()"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所在部门">
                      <el-select style="width: 100%;" v-model="form.deptName"
                                 placeholder="请选择所在部门" @change="$forceUpdate()" :disabled="isItMe()">
                        <el-option v-for="item in deptOptions" :key="item.deptId"
                                   :label="item.deptName" :value="item.deptName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="报销概述" prop="title">
                      <el-input v-model="form.title" placeholder="请输入报销概述" :readonly="isItMe()"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="报销时间" prop="businessDate">
                      <el-date-picker style="width: 100%;" clearable v-model="form.businessDate"
                                      type="date" value-format="yyyy-MM-dd" placeholder="请选择提交报销时间"
                                      :readonly="isItMe()">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="clStartTime">
                      <el-date-picker style="width: 100%;" v-model="form.clStartTime"
                                      type="datetime" clearable value-format="yyyy-MM-dd HH:00"
                                      format="yyyy-MM-dd HH:00" popper-class="hour-picker1"
                                      placeholder="请选择出差开始时间" @change="clStartTimeChange"
                                      :readonly="isItMe()">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间" prop="clEndTime">
                      <el-date-picker style="width: 100%;" v-model="form.clEndTime"
                                      type="datetime" clearable value-format="yyyy-MM-dd HH:00"
                                      format="yyyy-MM-dd HH:00" popper-class="hour-picker1"
                                      placeholder="请选择出差结束时间" @change="clEndTimeChange" :readonly="isItMe()">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="出差地点" prop="city">
                      <el-cascader style="width: 100%;" v-model="city" :options="cityData"
                                   :props="defaultPropsCa" @change='$forceUpdate()' clearable
                                   :disabled="isItMe()"></el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="途径地点" prop="passCity">
                      <el-cascader style="width: 100%;" v-model="passCity" :options="cityData"
                                   :props="defaultPropsCa" @change='$forceUpdate()' clearable
                                   :disabled="isItMe()"></el-cascader>
                    </el-form-item>
                  </el-col>
                </el-row>


                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="projectName">
                      <el-input v-model="form.projectName" placeholder="请输入项目名称"
                                :readonly="isItMe()"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="对应人员" prop="personnel">
                      <el-input v-model="form.personnel" placeholder="请输入对应人员"
                                :readonly="isItMe()"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </div>
            <el-card class="main-lf-b" :style="{height:form.type==1?'515px':'400px'}" shadow="never">
              <div class="label">报销信息</div>
              <el-table class="table" :data="tableData" :key="tableKey" border style="width: 100%">
                <el-table-column label="报销项目" align="center" prop="projectDictId" width="180">
                  <template slot-scope="scope">
                    <el-select @change="(e)=>{bxItemSelection(e,scope.row,scope.$index)}"
                               v-model="scope.row.projectDictId" placeholder="请选择" :disabled="isItMe()">
                      <el-option v-for="(item,ind) in projectData" :key="ind"
                                 :label="item.dictLabel" :value="item.dictValue">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="摘要" align="center" prop="purpose">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.purpose" placeholder="请输入摘要内容"
                              :readonly="isItMe()"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="amount" width="140">
                  <template slot-scope="scope">
                    <el-input @input="(e)=>{debounce(e,scope.row,scope.$index)}" type="number"
                              v-model="scope.row.amount" placeholder="请输入金额"
                              @blur="countAmount(scope.row)" :readonly="isItMe()"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="附件" align="center">
                  <template slot-scope="scope">
                    <div class="file-flex" v-for="(item,index) in scope.row.fileList" :key="index">
                      <!-- 表格内删除附件 -->
                      <div class="file-flex-close" v-if="!isItMe()">
                        <i class="el-icon-delete-solid"
                           @click="delFile(scope.row.fileList,index)"></i>
                      </div>
                      <el-image v-if="item.suffix != 'pdf'" style="width: 50px; height: 50px"
                                :src="upload.baseUrl + item.file"
                                :preview-src-list="[upload.baseUrl + item.file]">
                      </el-image>
                      <div v-else class="file-pdf"
                           @click="pdfPreview(upload.baseUrl + item.file)">
                        <img src="../../../assets/images/pdf.png" alt=""/>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" prop="date" v-if="!isItMe()" width="180">
                  <template slot-scope="scope">
                    <el-upload style="display: inline-block;margin-right: 5px;" :action="upload.url"
                               :headers="upload.headers" :on-success="fileSuccess"
                               :before-upload="beforeFile" :show-file-list="false"
                               :on-progress="fileProgress" multiple>
                      <el-button size="mini" type="text" icon="el-icon-folder-opened"
                                 @click="handleAnnex(scope.row,scope.$index)">
                        附件
                      </el-button>
                    </el-upload>
                    <el-button size="mini" type="text" icon="el-icon-close"
                               v-if="tableData.length != 1" @click="handleDelRow(scope.row,scope.$index)">
                      删除
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-plus"
                               v-if="tableData.length == (scope.$index + 1) && tableData.length < 6"
                               @click="handleAddRow(scope.row,scope.$index)">
                      增加
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>

            <el-dialog custom-class="pdfPreview" title="PDF预览" :visible.sync="filePdfShow" width="100vw"
                       append-to-body>
              <iframe :src="filePdfUrl" frameborder="0"></iframe>
            </el-dialog>

          </div>

          <div class="main-rt">
            <!-- 部门审批 -->
            <el-card class="box-card" shadow="never">
              <div class="label">部门审批</div>
              <el-form-item label="部门领导">
                <el-input v-model="bmNickName" disabled/>
              </el-form-item>
              <el-form-item label="部门意见" prop="deptLeaderPass">
                <el-select style="width: 100%;" v-model="form.deptLeaderPass" placeholder="请选择"
                           :disabled="disableBm()">
                  <el-option v-for="item in opinion" :key="item.value" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="审批时间" prop="deptLeaderAuthTime">
                <el-date-picker style="width: 100%;" v-model="form.deptLeaderAuthTime" type="datetime"
                                placeholder="选择日期时间" :disabled="disableBm()" value-format="yyyy-MM-dd hh:mm:ss"
                                @input="$forceUpdate()">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="审批理由" prop="deptLeaderRemarks">
                <el-input v-model="form.deptLeaderRemarks" :disabled="disableBm()"/>
              </el-form-item>
            </el-card>

            <!-- 领导审批 -->
            <el-card class="box-card" shadow="never">
              <div class="label">领导审批</div>
              <el-form-item label="审批领导">
                <el-input v-model="ldNickName" disabled/>
              </el-form-item>
              <el-form-item label="领导意见" prop="leaderPass">
                <el-select style="width: 100%;" v-model="form.leaderPass" placeholder="请选择"
                           :disabled="disableLd()">
                  <el-option v-for="item in opinion" :key="item.value" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="审批时间" prop="leaderAuthTime">
                <el-date-picker style="width: 100%;" v-model="form.leaderAuthTime" type="datetime"
                                placeholder="选择日期时间" :disabled="disableLd()" value-format="yyyy-MM-dd hh:mm:ss"
                                @input="$forceUpdate()">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="审批理由" prop="leaderRemarks">
                <el-input v-model="form.leaderRemarks" :disabled="disableLd()"/>
              </el-form-item>
            </el-card>
            <!-- 备注 -->
            <el-card class="box-card" shadow="never">
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入备注"
                          v-model="form.remarks" :readonly="form.status == 9"></el-input>
              </el-form-item>
            </el-card>
          </div>
        </el-form>

        <div class="footer">
          <div class="footer-num">合计：{{ totalAmount }}</div>
          <el-button type="primary" round v-if="form.status == 0" @click="twoSubmit(1)">保 存</el-button>
          <el-button type="primary" round v-if="form.status !== 9" @click="twoSubmit(2)">提 交</el-button>
          <el-button type="primary" round v-if="form.status == 9" @click="printPreview(form)">打印单据</el-button>
        </div>
      </div>
      <el-dialog title="单据打印预览" custom-class="printPreview" :visible.sync="printShow" width="297mm"
                 append-to-body>
        <bxTemplate :rowData="rowData"></bxTemplate>
      </el-dialog>
    </div>
  </transition>
</template>

<script>
  import {
    listAll,
    getBxExpense,
    addBxExpense,
    updateBxExpense,
    playBwtTime
  } from "@/api/business/bxExpense";

  import {
    getDicts
  } from "@/api/system/dict/data"

  import {
    getToken
  } from '@/utils/auth'

  import {
    listBxCity
  } from "@/api/business/bxCity"

  import {
    getConfig,
  } from "@/api/system/config";

  import bxTemplate from "../bxClTemplate/index.vue"

  export default {
    props: {
      title: {
        type: String,
        default: "",
      },
    },
    components: {
      bxTemplate
    },
    data() {
      return {
        // 是否加载
        loading: false,
        // 加载时的标题
        loadingTitle: "",
        // 是否编辑
        isEdit: false,
        // 当前步骤
        active: 0,
        // 用户角色
        roles: [],
        // 当前用户
        nickName: "",
        // 所在部门
        deptName: "",
        // 部门树选项
        deptOptions: undefined,
        // 表单参数
        form: {},
        // 差旅地点
        cityData: [],
        // 差旅地点数据格式处理
        defaultPropsCa: {
          children: "children",
          value: 'cityName',
          label: "cityName",
          multiple: true,
          checkStrictly: true
        },
        // 出差地点
        city: "",
        // 途径地点
        passCity: "",
        // 对应人员
        personnel: "",
        // 表单校验
        rules: {
          title: [{
            required: true,
            message: "报销概述不能为空",
            trigger: "blur"
          }],
          businessDate: [{
            required: true,
            message: "报销时间不能为空",
            trigger: "blur"
          }],
          clStartTime: [{
            required: true,
            message: "开始时间不能为空",
            trigger: "blur"
          }],
          clEndTime: [{
            required: true,
            message: "结束时间不能为空",
            trigger: "blur"
          }],
        },
        // 报销项目数据
        projectData: [],
        // 加油比例配置
        refuelConfig: 0,
        // 报销单据信息
        tableData: [{
          // 主表ID
          expenseId: null,
          // 项目ID
          projectDictId: null,
          // 摘要
          purpose: null,
          // 金额
          amount: null,
          // 附件
          fileList: [],
        }],
        tableKey: 0,
        // 当前上传附件的信息,每上传一条清空一下
        fileInfo: {},
        // 报销项目数据
        projectData: [],
        // 附件弹窗
        fileShow: false,
        // 附件弹窗标题
        fileTitle: "",
        // 上传
        upload: {
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 回显
          baseUrl: process.env.VUE_APP_BASE_API,
        },
        // PDF预览
        filePdfShow: false,
        // PDF预览地址
        filePdfUrl: "",
        // 领导意见
        opinion: [{
          label: "同意",
          value: 1
        },
          {
            label: "驳回",
            value: 0
          }
        ],
        // 审批领导
        ldNickName: "",
        // 部门领导
        bmNickName: "",
        // 合计金额
        totalAmount: 0,
        //防抖timer
        timer: null,
        // 打印预览弹窗
        printShow: false,
        // 要打印的数据
        rowData: [],
      }
    },
    methods: {
      initPage(val) {
        // 从vuex(状态)中获取当前用户有哪些角色
        this.roles = this.$store.getters.roles;
        /** 查询部门下拉树结构 */
        listAll().then(response => {
          this.deptOptions = response.data;
        });
        // 获取差旅项目字典
        getDicts('cl').then(res => {
          this.projectData = res.data;
        })
        // 根据val判断是新增还是修改
        if (val.isAdd == "add") {
          // 是否编辑
          this.isEdit = false;
          // 获取当前用户
          this.nickName = this.$store.state.user.nickName;
          // 获取当前用户所在部门
          this.form.deptName = this.$store.state.user.deptName;
          // 新增时获取传来的type
          this.form.type = val.type;
        } else {
          // 是否编辑
          this.isEdit = true;
          // 如果是编辑直接改步骤
          this.active = 1
          // 获取用户
          this.nickName = val.nickName;
          // 获取主要信息
          this.mainInfo(val.id);
        }
        // 获取配置信息-加油费核算比例
        getConfig(100).then((response) => {
          this.refuelConfig = response.data.configValue
        })
        // 获取差旅地点
        listBxCity().then(res => {
          this.cityData = this.handleTree(res.data, "id", "parentId");
        })
      },
      // 出差开始时间
      clStartTimeChange(val) {
        this.$forceUpdate()
        if (this.form.clEndTime !== undefined && this.form.clEndTime !== null) {
          this.form.clStartTime = val
          this.compareTimes(this.form.clStartTime, this.form.clEndTime, 'clearFs')

        }
      },
      // 出差结束时间
      clEndTimeChange(val) {
        this.$forceUpdate()
        if (this.form.clStartTime !== undefined && this.form.clStartTime !== null) {
          this.form.clEndTime = val
          this.compareTimes(this.form.clStartTime, this.form.clEndTime, 'clearFe')
        }
      },
      // 时间比较
      compareTimes(startTime, endTime, clearType) {
        const startDateTime = new Date(startTime.replace(/-/g, '/'));
        const endDateTime = new Date(endTime.replace(/-/g, '/'));
        if (startDateTime > endDateTime) {
          this.$message.error('开始时间必须小于结束时间');
          //清空超时时间
          if (clearType == 'clearFe') {
            this.form.clEndTime = null
          }
          if (clearType == 'clearFs') {
            this.form.clStartTime = null
          }
          //清除出差餐补助
          this.tableData.map((ele, index) => {
            if (ele.projectDictId == 'bz') {
              this.tableData.splice(index, 1)
            }
          })
        } else {
          //获取工作日与休息日天数补助金额
          playBwtTime({
            startTime,
            endTime
          }).then(res => {
            if (res.code == 200 && 'data' in res && res.data > 0) {
              let isHas = false
              this.tableData.map(ele => {
                if (ele.projectDictId == 'bz') {
                  isHas = true
                  ele.amount = res.data // 金额
                }
              })
              //添加补助
              if (!isHas) {
                this.tableData.push({
                  expenseId: this.form.id, // 主表ID
                  projectDictId: 'bz', // 项目ID
                  purpose: null, // 摘要
                  amount: res.data, // 金额
                  fileList: [], // 附件
                })
              }
              //计算金额
              this.countAmount()
            }
          })
        }
      },
      // 第一步提交
      submitOne() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.city.length > 0) {
              this.form.city = JSON.stringify(this.city)
            }
            if (this.passCity.length > 0) {
              this.form.passCity = JSON.stringify(this.passCity)
            }
            if (this.personnel.length > 0) {
              this.form.personnel = JSON.stringify(this.personnel)
            }
            addBxExpense(this.form).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.mainInfo(res.data.id);
            });
          }
        });
      },
      // 获取主要信息
      mainInfo(id) {
        // 查询前先清除表单
        this.form = {};
        // 获取主表详细信息
        getBxExpense(id).then(res => {
          // 切换步骤
          this.active = 1;
          // 表单赋值
          this.form = res.data;
          // 解析出差地点方便回显
          if (res.data.city) {
            this.city = JSON.parse(res.data.city);
          }
          // 解析途径地点方便回显
          if (res.data.passCity) {
            this.passCity = JSON.parse(res.data.passCity);
          }
          // 解析对应人员
          if (res.data.personnel) {
            this.personnel = JSON.parse(res.data.personnel);
          }
          // 判断报销单据表格数据是否存在
          if (res.data.recordList !== undefined) {
            res.data.recordList.forEach((item, index) => {
              if (item.fileList == undefined) {
                item.fileList = [];
              }
            })
            this.tableData = res.data.recordList;
            // 调用计算金额
            // this.countAmount();
            let num = 0;

            this.tableData.forEach((item, index) => {
              num += Number(item.amount);
            });

            // 保留两位小数并使用千位分隔符格式化
            this.totalAmount = num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
          }

          // 判断领导是否审批
          if (!this.disableLd() && (res.data.status == 1 || res.data.status == 2)) {
            // 初始化数据
            this.form.leaderAuthTime = this.parseTime(new Date().getTime(), '{y}-{m}-{d} {h}:{i}:{s}');
            this.ldNickName = this.$store.state.user.nickName;
          }

          // 判断部门领导是否审批
          if (!this.disableBm() && res.data.status == 1) {
            // 初始化数据
            this.form.deptLeaderAuthTime = this.parseTime(new Date().getTime(),
              '{y}-{m}-{d} {h}:{i}:{s}');
            this.bmNickName = this.$store.state.user.nickName;
          }

          if (res.data.leaderUser !== undefined) {
            this.ldNickName = res.data.leaderUser.nickName;
          }

          if (res.data.deptLeaderUser !== undefined) {
            this.bmNickName = res.data.deptLeaderUser.nickName;
          }
        })
      },
      // 报销项目选择
      bxItemSelection(e, item, index) {
        let isHasTxf = false
        let isHasJyf = false
        this.tableData.map(ele => {
          if (ele.projectDictId == 'txf') {
            isHasTxf = true
          }
          if (ele.projectDictId == 'jyf') {
            isHasJyf = true
          }
        })
        //是否添加加油费
        if (!isHasJyf && isHasTxf) {
          if (this.tableData.length == 6) {
            this.$notify({
              title: '抱歉',
              message: '通行费单据需关联计算，请先删除其他单据后再添加通行费单据~',
              type: 'warning'
            });
            item.projectDictId = null;
            return
          }

          let isBz = false;
          // 检查是否已存在 'bz' 行
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].projectDictId === 'bz') {
              isBz = true;
              this.tableData.splice(i, 0, {
                expenseId: this.form.id,
                projectDictId: 'jyf',
                purpose: null,
                amount: null,
                fileList: [],
              });
              break;
            }
          }
          if (!isBz) {
            // 如果不存在 'bz' 行，直接添加新数据
            this.tableData.push({
              expenseId: this.form.id, // 主表ID
              projectDictId: 'jyf', // 项目ID
              purpose: null, // 摘要
              amount: null, // 金额
              fileList: [], // 附件
            })
          }
        }
        this.countAmount()
      },
      // 添加附件
      handleAnnex(row, index) {
        this.fileTitle = `上传第${index + 1}条报销附件：`
        this.fileInfo = row;
      },
      // 附件开始上传
      fileProgress() {
        this.loading = true;
        this.loadingTitle = "附件努力上传中~"
      },
      // 附件上传成功
      fileSuccess(res, file) {
        this.fileInfo.fileList.push({
          // 附件链接
          file: res.fileName,
          // 附件后缀
          suffix: file.raw.type.split('/')[1],
          // 附件名称
          fileName: file.name,
        })

        this.tableKey = Math.random()

        this.loading = false;
        this.$message({
          message: `${file.name}--上传成功`,
          type: 'success'
        });
      },
      // 附件上传校验
      beforeFile(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
        const isPDF = file.type === 'application/pdf';
        const isLt50M = file.size / 1024 / 1024 < 50;
        if (!(isImage || isPDF)) {
          this.$message.error('上传文件只能是 JPG、PNG 或 PDF 格式!');
        }
        if (!isLt50M) {
          this.$message.error('上传文件大小不能超过 50MB!');
        }
        this.loading = false;
        return (isImage || isPDF) && isLt50M;
      },
      // PDF预览
      pdfPreview(val) {
        this.filePdfUrl = val;
        this.filePdfShow = true;
      },
      // 删除文件
      delFile(row, index) {
        row.splice(index, 1);
      },
      // 增加报销
      handleAddRow(row) {
        if (row.projectDictId == null || row.amount == null) {
          this.$notify({
            title: '抱歉',
            message: '请先填报此条记录后再增加~',
            type: 'warning'
          });
          return;
        }

        let isBz = false;
        // 检查是否已存在 'bz' 行
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].projectDictId === 'bz') {
            isBz = true;
            this.tableData.splice(i, 0, {
              expenseId: this.form.id,
              projectDictId: null,
              purpose: null,
              amount: null,
              fileList: [],
            });
            break;
          }
        }
        if (!isBz) {
          // 如果不存在 'bz' 行，直接添加新数据
          this.tableData.push({
            expenseId: this.form.id,
            projectDictId: null,
            purpose: null,
            amount: null,
            fileList: [],
          });
        }
      },
      // 删除报销
      handleDelRow(row, index) {
        if (this.tableData.length == 1) {
          this.$notify({
            title: '抱歉',
            message: '必须保持有一条记录~',
            type: 'warning'
          });
          return
        }
        this.tableData.splice(index, 1);
        // 调用计算金额
        this.countAmount();
      },
      // 防抖函数
      debounce(e, row, index) {
        // const that = this
        // if (this.timer) {
        // 	clearTimeout(this.timer)
        // }
        // this.timer = setTimeout(() => {
        // 	that.countAmount() //防抖计算费用
        // })
      },
      // 计算金额
      countAmount(val) {
        let num = 0;
        if (val !== undefined && val.projectDictId == 'jyf') {
          this.tableData.forEach((item, index) => {
            num += Number(item.amount);
          });
        } else {
          if (this.tableData[0].amount !== null) {
            // 获取通行总费用
            let txfMoneySum = 0;
            this.tableData.forEach((item, index) => {
              if (item.projectDictId === 'txf') {
                txfMoneySum += Number(item.amount);
              }
            });

            // 计算加油费用
            this.tableData.forEach((item, index) => {
              if (item.projectDictId === 'jyf') {
                item.amount = parseFloat((txfMoneySum * this.refuelConfig).toFixed(2));
              }
              num += Number(item.amount);
            });
          }
        }
        // 保留两位小数并使用千位分隔符格式化
        this.totalAmount = num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      },
      // 领导审批
      disableLd() {
        let isAllow = true;
        if (this.form.status !== 9 && this.form.status !== 0) {
          isAllow = !this.hasRole(['admin', 'BOSS'])
        }
        return isAllow;
      },
      // 部门审批
      disableBm() {
        let isAllow = true;
        if (this.form.status !== 9 && this.form.status !== 0) {
          if (this.hasRole(['BOSS'])) {
            isAllow = true;
          } else {
            isAllow = !this.hasRole(['admin', 'DEPT_LEADER'])
          }
        }
        return isAllow;
      },
      // 是否本人,如果是本人才能编辑主表信息以及报销单据
      isItMe() {
        const userId = this.$store.state.user.userId;
        return !(this.form.status == 0 && this.form.uid == userId)
      },
      // val ==1 本人保存单据    val == 2提交审批
      twoSubmit(val) {
        this.loading = true;
        this.loadingTitle = "努力提交中~"
        this.form.recordList = this.tableData;

        if (this.city.length > 0) {
          this.form.city = JSON.stringify(this.city)
        }
        if (this.passCity.length > 0) {
          this.form.passCity = JSON.stringify(this.passCity)
        }
        if (this.personnel.length > 0) {
          this.form.personnel = JSON.stringify(this.personnel)
        }

        // if (this.form.deptLeaderPass != undefined && this.form.deptLeaderPass == 0) {
        // 	this.form.status = 1;
        // 	updateBxExpense(this.form).then(response => {
        // 		this.loading = false;
        // 		this.$modal.msgSuccess("提交成功");
        // 		this.goBack();
        // 	}).catch(() => {
        // 		this.loading = false;
        // 	});
        // 	return
        // } else if (this.form.leaderPass != undefined && this.form.leaderPass == 0) {
        // 	this.form.status = 2;
        // 	updateBxExpense(this.form).then(response => {
        // 		this.loading = false;
        // 		this.$modal.msgSuccess("提交成功");
        // 		this.goBack();
        // 	}).catch(() => {
        // 		this.loading = false;
        // 	});
        // 	return
        // }

        if (val == 1) {
          updateBxExpense(this.form).then(response => {
            this.loading = false;
            this.$modal.msgSuccess("保存成功");
            this.goBack();
          }).catch(() => {
            this.loading = false;
          });
        } else {
          if (this.form.status == 0) {
            this.form.status = 1;
          } else {
            if (this.form.leaderPass == undefined && this.form.deptLeaderPass == undefined) {
              this.loading = false;
              this.$message({
                message: '请填写审核内容~',
                type: 'warning'
              });
              return
            }
            if (this.form.leaderPass == 0) {
              this.form.status = 0;
              this.form.leaderId = this.$store.state.user.userId;
            } else if (this.form.deptLeaderPass == 0) {
              this.form.status = 0;
              this.form.deptLeaderId = this.$store.state.user.userId;
            } else if (this.form.leaderPass == 1) {
              this.form.status = 9;
              this.form.leaderId = this.$store.state.user.userId;
            } else {
              this.form.status = 2;
              this.form.deptLeaderId = this.$store.state.user.userId;
            }
          }
          updateBxExpense(this.form).then(response => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功");
            this.goBack();
          }).catch(() => {
            this.loading = false;
          });
        }
      },
      // 打印单据
      printPreview(row) {
        this.printShow = true;
        this.rowData = row;
      },
      // 返回列表页
      goBack() {
        this.$emit("close");
      },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
    height: calc(100% - 60px);
    position: absolute !important;
    z-index: 999;
    top: 0;
    left: 0;
    background: #FAFAFA;
    padding: 20px;

    .footer {
      width: 100%;
      height: 60px;
      position: fixed;
      left: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 0 50px;
      background-color: #ffffff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

      .footer-num {
        color: #5493FB;
        font-size: 18px;
        font-weight: bold;
        margin-right: 28px;
      }
    }

    .label {
      font-size: 16px;
      font-family: Source Han Sans CN;
      font-weight: bold;
      color: #409EFF;
      margin-bottom: 22px;
    }
  }

  .main-header {
    margin-bottom: 20px;
  }

  ::v-deep .steps-box-card {
    margin-bottom: 10px;

    .el-card__body {
      padding: 15px 20px 8px 20px;
    }
  }

  .main-steps {
    width: 50%;
    margin: 0 auto;
  }

  .main-flex {
    height: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
  }

  ::v-deep .main-lf {
    width: calc(100% - 350px);
    height: 100%;
    padding-right: 10px;

    .main-lf-t {
      margin-bottom: 10px;
    }

    .main-lf-t .el-card__body {
      padding: 15px 20px 0px 20px;
    }

    .main-lf-b {
      overflow-y: auto;
    }

    .main-lf-b::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }

    /*正常情况下滑块的样式*/
    .main-lf-b::-webkit-scrollbar-thumb {
      width: 5px;
      background-color: rgba(0, 0, 0, .05);
      border-radius: 10px;
      -webkit-box-shadow: inset1px1px0rgba(0, 0, 0, .1);
    }

    /*正常时候的主干部分*/
    .main-lf-b::-webkit-scrollbar-track {
      width: 5px;
      border-radius: 10px;
      -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0);
      background-color: white;
    }

  }

  ::v-deep .main-rt {
    width: 350px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .box-card {
      margin-bottom: 12px;

      .el-card__body {
        padding: 15px 20px 0 20px;
      }
    }
  }

  ::v-deep .el-image {
    margin-right: 2px;
  }

  ::v-deep .el-image:last-child {
    margin-right: 0px;
  }

  ::v-deep .el-dialog__body {
    overflow: hidden;
  }

  .file-flex {
    display: inline-block;
    margin-right: 8px;
    position: relative;
  }

  .file-flex-close {
    position: absolute;
    top: -5px;
    right: 0;
    cursor: pointer;
    z-index: 9999;
    display: none;
  }

  .file-flex:hover {
    .file-flex-close {
      display: block;
    }
  }

  .file-flex:last-child {
    margin-right: 0px;
  }

  .file-pdf {
    width: 50px;
    height: 50px;
    cursor: pointer;
  }

  .file-pdf img {
    width: 100%;
    height: 100%;
  }

  ::v-deep .pdfPreview {
    width: 100vw;
    height: 100vh;
    margin-top: 0 !important;
    background-color: rgb(82, 86, 89);

    .el-dialog__title {
      color: #f3f3f3;
    }


    .el-dialog__body {
      width: 100%;
      height: calc(100% - 54px);
    }

    .el-dialog__body iframe {
      width: 100%;
      height: 100%;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: #f3f3f3 !important;
    }
  }

  ::v-deep .table .el-input.is-disabled .el-input__inner {
    background-color: #ffffff !important;
    border-color: #DCDFE6;
    color: #606266;
  }

  ::v-deep .printPreview {
    height: 800px;
    overflow: hidden;
    background-color: rgb(82, 86, 89);

    .el-dialog__title {
      color: #f3f3f3;
    }

    .el-dialog__body {
      width: 100%;
      height: calc(100% - 54px);
      overflow-y: auto;
      position: relative;
    }
  }
</style>
<style lang="scss" scope>
  .hour-picker1 {
    .el-scrollbar:nth-of-type(2) {
      display: none !important;
    }

    .el-scrollbar:nth-of-type(3) {
      display: none !important;
    }

    .el-time-spinner__wrapper {
      width: 100% !important;
    }
  }
</style>
